/*
 * @Description:
 * @Author: wangfuwei
 * @Date: 2020-12-02 21:35:06
 * @LastEditors: wangfuwei
 * @LastEditTime: 2020-12-08 19:09:10
 * @FilePath: /horizon-frontend/src/components/SettingDrawer/themeColor.js
 */

import client from "webpack-theme-color-replacer/client";
import generate from "@ant-design/colors/lib/generate";
import { colorToRgb, rgbToHex, appendStyle } from "@/utils/util";

export default {
  getAntdSerials(color) {
    // 淡化（即less的tint）
    // eslint-disable-next-line
    const lightens = new Array(9).fill().map((t, i) => {
      return client.varyColor.lighten(color, i / 10);
    });
    // colorPalette变换得到颜色值
    const colorPalettes = generate(color);
    return lightens.concat(colorPalettes);
  },
  changeColor(newColor) {
    topLayoutMenuStyle(newColor);

    var options = {
      newColors: this.getAntdSerials(newColor), // new colors array, one-to-one corresponde with `matchColors`
      changeUrl(cssUrl) {
        return `/${cssUrl}`; // while router is not `hash` mode, it needs absolute path
      },
    };
    return client.changer.changeColor(options, Promise);
  },
};

/**
 * 初始化头部布局Style
 */
function topLayoutMenuStyle(newColor) {
  const offset = 20; //颜色渐变偏移量
  const opacity_bg = 0.15; //头部菜单鼠标滑过背景色透明度
  const opacity_icon = 0.5; //头部菜单锁定图标背景色透明度

  let color = colorToRgb(newColor);
  let color_ = color.split(",");

  let R = parseInt(color_[0]) + offset > 255 ? 255 : parseInt(color_[0]) + offset;
  let G = parseInt(color_[1]) + offset > 255 ? 255 : parseInt(color_[1]) + offset;
  let B = parseInt(color_[2]) + offset > 255 ? 255 : parseInt(color_[2]) + offset;
  let color1 = rgbToHex(R, G, B);

  R = parseInt(color_[0]) - offset < 0 ? 0 : parseInt(color_[0]) - offset;
  G = parseInt(color_[1]) - offset < 0 ? 0 : parseInt(color_[1]) - offset;
  B = parseInt(color_[2]) - offset < 0 ? 0 : parseInt(color_[2]) - offset;
  let color2 = rgbToHex(R, G, B);

  const id = "TopLayout_Menu_Style";
  let style = `.toplayout-menu-item.ant-menu-item-active:not(.ant-menu-item-selected) { background:rgba(${color},${opacity_bg})}`;
  style += `.toplayout-menu-item.ant-menu-item-active:not(.ant-menu-item-selected) .icon { color:rgba(${color},${opacity_icon})}`;
  style += `.toplayout-menu-item.ant-menu-item-selected { background: linear-gradient(135deg, ${color1} 0%, ${color2} 100%)}`;
  appendStyle(id, style);
}
